﻿using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using FortuneUniverse.Fortune.Dyson;
using Newtonsoft.Json;

namespace FortuneUniverse
{
    public static class Application
    {
        public static void Main(string[] args)
        {
            Parallel.For(0, 10, index =>
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                GameDesc gameDesc = new GameDesc();
                gameDesc.SetForNewGame(1, 64);
                JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings
                {
                    DefaultValueHandling = DefaultValueHandling.Ignore
                };
                
                GalaxyData galaxyData = UniverseGen.CreateGalaxy(gameDesc);
                File.WriteAllText($"./{gameDesc.galaxySeed}-{gameDesc.starCount}.json", JsonConvert.SerializeObject(galaxyData, Formatting.Indented, jsonSerializerSettings));
                Console.Out.WriteLine($"write json success, cost {stopwatch.ElapsedMilliseconds}ms, thread id={Thread.CurrentThread.ManagedThreadId}");
                stopwatch.Stop();
            });
            // Stopwatch stopwatch = new Stopwatch();
            // stopwatch.Start();
            // for (int i = 0; i < 10; i++)
            // {
            //     ThreadPool.QueueUserWorkItem(doGen, i);
            // }
            //
            // while (true)
            // {
            //     Thread.Sleep(1000);//这句写着，主要是没必要循环那么多次。去掉也可以。
            //     ThreadPool.GetMaxThreads(out int maxWorkerThreads, out int _);
            //     ThreadPool.GetAvailableThreads(out int workerThreads, out int _);
            //     if (maxWorkerThreads - workerThreads != 0) continue;
            //     Console.WriteLine("结束了");
            //     break;
            // }
            // Console.Out.WriteLine($"totally cost {stopwatch.ElapsedMilliseconds}ms");
            // stopwatch.Stop();
        }

        public static void doGen(object index)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            GameDesc gameDesc = new GameDesc();
            gameDesc.SetForNewGame((int) index, 64);
            JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings
            {
                DefaultValueHandling = DefaultValueHandling.Ignore
            };
                
            GalaxyData galaxyData = UniverseGen.CreateGalaxy(gameDesc);
            File.WriteAllText($"./{gameDesc.galaxySeed}-{gameDesc.starCount}.json", JsonConvert.SerializeObject(galaxyData, Formatting.Indented, jsonSerializerSettings));
            Console.Out.WriteLine($"write json success, cost {stopwatch.ElapsedMilliseconds}ms, thread id={Thread.CurrentThread.ManagedThreadId}");
            stopwatch.Stop();
        }
    }
}